// import fetch from 'isomorphic-fetch'

import 'whatwg-fetch';
import * as types from './ActionTypes';
import 'es6-promise';
import {hashHistory } from 'react-router'

//获取用户登录状态和用户id
export const user_logined = (type,userId,userTel) =>{
  return dispatch=>dispatch({type:types.USER_LOGINED,getData:type,userId:userId||0,userTel:userTel})
}

export const checkArr = (arr)=>{
  return dispatch=>dispatch({type:types.CHECKED_ARR,getData:arr})
}
/**
 * get请求
 * @param  {String} options.url   api地址
 * @param  {String} options.query query参数
 * @return {Promise}               Promise
 */
const _get = ({ url, query },dispatch) => {
  dispatch({type:types.START_LOADING})
  let _url
  if (query) {
    _url = `http://120.27.37.54${url}?${query}`
  } else {
    _url = `http://120.27.37.54/${url}`
  }
  console.log(_url)
  return fetch(_url,{
        method: 'GET',
        mode: 'cors',
        cache: 'default'
      })
    .then(res => {
      dispatch({type:types.FINISH_LOADING})
      if (res.status >= 200 && res.status < 300) {
        return res.json()
      }
      return Promise.reject(new Error(res.status));
    })
}

// 查询项目分类
export const itemClass_show = () => {
 const url = 'mb/itemClass/show';
 return (dispatch) =>{
   _get({url},dispatch)
     .then((json) => {
       if(json.msg === '操作成功'){
         dispatch({type:types.ITEMCLASS_SHOW, getData:json.data.list})
       }
       // return Promise.reject(new Error('fetch fail'))
     })
     .catch((error) => {
       // dispatch({type:types.FETCH_COMING_SOON_FAIL})
       return Promise.reject(error)
     })
 }
}

/**
 * 获取首页信息
 * @param  {Function} options.dispatch store对象解构出来的函数，无需手动提供
 * @param  {Number} page             页数
 * @param  {Number} count             每页数量
 * @return {Promise}                  Promise
 */
 export const index_data = (page,count) => {
  const url = '/index';
  return (dispatch) =>{
    _get({url},dispatch)
      .then((json) => {
        if(json.status === 'ok'){
          dispatch({type:types.FETCH_INDEX_DATA, index_data:json})
        }
        // return Promise.reject(new Error('fetch fail'))
      })
      .catch((error) => {
        // dispatch({type:types.FETCH_COMING_SOON_FAIL})
        return Promise.reject(error)
      })
  }
}

//资讯分类列表接口
export const news_cms_class_list = () => {
  const query = ``;
  return (dispatch)=>{
    fetch("http://120.27.37.54/news_cms/class/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      // console.log(res.data.list)
      dispatch({type:types.NEWS_CMS_CLASS_LIST, getData:res.data.list})
    });
  }
}
//资讯文章列表
export const news_cms_art_list = (acId) => {
  const query = (acId)?'ac_id='+acId:'';
  return (dispatch)=>{
    fetch("http://120.27.37.54/news_cms/article/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      dispatch({type:types.NEWS_CMS_ART_LIST, getData:res.data.list})
    });
  }
}



/**
 *   them_hos_data
 * @param  {Function} options.dispatch store对象解构出来的函数，无需手动提供
 * @param  {Number} page             页数
 * @param  {Number} count             每页数量
 * @return {Promise}                  Promise
 */
 // 甄选 - > 医院列表
 export const them_hos_data = (page,count) => {
  const url = '/mb/hospital';
  const query = `pageSize=${page}&pageNo=${count}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_HOS, getData:json})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}
 // 甄选 - > 医院列表 ->医院详情
export const mall_them_hos_det = (hospitalId) => {
 const url = '/mb/hospital/show';
 const query = `hospitalId=${hospitalId}`
 return (dispatch) =>{
   _get({url,query},dispatch)
     .then((json) => {
       if(json.msg === '操作成功'){
         dispatch({type:types.FETCH_MALL_THEM_HOS_DET, getData:json.data.list})
       }
     })
     .catch((error) => {
       return Promise.reject(error)
     })
 }
}
// 甄选 - > 医院列表 ->医院详情 ->服务项目
export const mall_them_hos_servItem = (obj) => {
  const url = '/mb/itemPro/show';
  // console.log(!!obj.hospit == false)
  let query = '';
  // if(obj && obj.hospitalId){
  //   query += `hospitalId=${obj.hospitalId}`
  // }
  // if(obj && obj.icId){
  //   query += `icId=${obj.icId}`
  // }
  if(obj){
    for(let i in obj){
      query += i + '=' +obj[i] + '&'
    }
  }
  // if(obj && obj.pageSize){
  //   query += `pageSize=${obj.pageSize}&pageNo=${obj.pageNo}`
  // }
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.code === '40300'){
          dispatch({type:types.FETCH_MALL_THEM_HOS_SERVITEM, getData:json.data.list})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
    }
}
// 医院列表 ->医院详情 ->医生信息
export const mall_them_doc_show = (hospitalId) => {
  const url = '/mb/doctor/show';
  const query = `hospitalId=${hospitalId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_DOC_SHOW, getData:json.data.list})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}
// 甄选 - > 医院列表 ->医院详情 ->服务项目-详情
export const mall_them_hos_servItem_det = (itemId) => {
  const url = '/mb/itemPro/detail';
  const query = `itemId=${itemId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_HOS_SERVITEM_DET, getData:json.data})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
    }
}
//pageSize 多少条
//pageno 多少页
// 甄选 - > 医生列表
export const them_doc_data = (page,count) => {
 const url = '/mb/doctor';
 const query = `pageSize=${page}&pageNo=${count}`
 return (dispatch) =>{
   _get({url,query},dispatch)
     .then((json) => {
       if(json.code === '40300'){
         console.log(json);
         dispatch({type:types.FETCH_MALL_THEM_DOC, getData:json.data.list})
       }
     })
     .catch((error) => {
       return Promise.reject(error)
     })
 }
}
// 甄选 - > 医生列表 -> 医生详情
export const mall_them_doc_det = (doctorId) => {
  const url = '/mb/doctor/detail';
  const query = `doctorId=${doctorId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        console.log(json);
        if(json.code === '40300'){
          dispatch({type:types.FETCH_MALL_THEM_DOC_DET, getData:json.data.list})
        }else{
          alert(json.msg)
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}

// 查询项目详情里面的   相关案例
export const servItem_caseList = (itemId) => {
  const url = '/shopping_mall/case';
  const query = `item_id=${itemId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.code == '200'){
          console.log(json.data.list);
          dispatch({type:types.FETCH_MALL_THEM_ANLI, getData:json.data.list})
        }else{
          dispatch({type:types.FETCH_MALL_THEM_ANLI, getData:[]})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}


//加入购物车
export const add_shopcar = (userId,hospitalId,itemId,itemNum) => {
  const query = `user_id=${userId}&hospital_id=${hospitalId}&item_id=${itemId}&item_num=${itemNum}`
    fetch("http://120.27.37.54/shopping_mall/cart/add", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    });
}

export const itemPro = ()=>{
  const url = '/mb/itemPro';
  return (dispatch) => {
    _get({url},dispatch)
    .then((json) => {
      if(json.msg === '操作成功'){

        dispatch({type:types.ITEM_PRO, getData:json.data.list})
      }
    })
    .catch((error) => {
      return Promise.reject(error)
    })
  }
}
// 生成订单
// http://120.27.37.54/shopping_mall/order/gen?param={"user_phone": 15011095069,"cart_list":
// [{"cart_id": 0,"user_id": 1,"item_price": 2380,"item_num": 3,"item_id": 2,"hospital_id": 49,"doctor_id": 10,
// "item_name": "爱芙莱玻尿酸（0.5ML/次）","order_from": 1,"item_image": "148456874754.jpg"}
export const pro_order_list = (user_phone,myconfig) => {
  let param = {
    "user_phone":user_phone,
    "cart_list":myconfig
  };
  console.log(param)
  fetch("http://120.27.37.54/shopping_mall/order/gen", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      body: "param="+JSON.stringify(param)
    }).then(function(res) {
      console.log(res);
      console.log("param="+JSON.stringify(param))
      if (res.ok) {
        return res.json();
        console.log("success");
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      console.log(res)
      // hashHistory.push('/user/pay/'+res.data.unionSN)
    });
}


//获取 or 更新用户购物车中未支付的物品
export const get_add_shopcar = (userId,callback) => {
  const query = `user_id=${userId}`;
  return (dispatch) => {
    fetch("http://120.27.37.54/shopping_mall/cart/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      dispatch({type:types.USER_SHOP_LIST, getData:res.data});
      if(callback){
        callback();
      }
    });
  }
}

//获取用户购物车中未支付的物品
export const dele_shop_order = (cart_id,callBack) => {
  const query = cart_id;
  return (dispatch) => {
    fetch("http://120.27.37.54/shopping_mall/cart/"+query, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/form-data"
      },
      body: ''
    }).then(function(res) {
      if (res.ok) {
        console.log("删除成功");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      if(callBack)callBack();
    });
  }
}


//分页获取或更新订单列表
export const get_order_classify = (user_id) => {
  const query = `user_id=${user_id}`;
  return (dispatch)=>{
    dispatch({type:types.START_LOADING})
    fetch("http://120.27.37.54/shopping_mall/order/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    })
    .then(function(res){
      let data_list = !!res.data?res.data.list:[];
      dispatch({type:types.FINISH_LOADING})
      dispatch({type:types.GET_ORDER_CLASSIFY, getData:data_list})
    });
  }

}
